'use strict';

const fs = require('fs');
const path = require('path');
const router = require('koa-router')();

function getFile(){
    let files = fs.readdirSync(__dirname);

    let js_files = files.filter(item =>{
        return item.endsWith('.js') && item !== 'index.js';
    })

    return js_files;
}

function registerRouter(file){
    file.forEach(element => {
        let filePath = path.join(__dirname,element);
        let routerObj = require(filePath);

        for(let item in routerObj){
            let arr = routerObj[item];
            let type = arr[0];

            if(type === 'get'){
                if(arr.length===2){
                    let fn = arr[1];  
                    router.get(item,fn);
                }else{
                    let auth = arr[1];
                    let fn = arr[2];
                    router.get(item,auth,fn);
                }
            }else if(type === 'post'){
                if(arr.length===2){
                    let fn = arr[1];  
                    router.post(item,fn);
                }else{
                    let auth = arr[1];
                    let fn = arr[2];
                    router.post(item,auth,fn);
                }
            }
        }
    });
}


module.exports = function(){
    let file = getFile();
    registerRouter(file);
    return router.routes();
}